package application;

import application.authorization.RolesSession;
import application.authorization.UserRolesAuthorizer;
import application.resources.ImageResource;
import org.apache.wicket.*;
import org.apache.wicket.authentication.AuthenticatedWebApplication;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.authorization.strategies.role.RoleAuthorizationStrategy;
import org.apache.wicket.authorization.strategies.role.metadata.MetaDataRoleAuthorizationStrategy;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.protocol.http.WebResponse;
import org.apache.wicket.request.IRequestCycleProcessor;
import org.apache.wicket.settings.IRequestLoggerSettings;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.apache.wicket.util.time.Duration;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.wicketstuff.annotation.scan.AnnotatedMountScanner;
import web.admin.AdminPage;
import web.cms.HomePage;
import web.eshop.MultipleProductsEshopPage;
import web.eshop.SimpleProductEshopPage;
import web.eshop.order.OrderPage;
import web.eshop.wizard.RegisteredWizardPage;
import web.login.LoginPage;
import web.login.UserSettingsPage;

import javax.servlet.http.HttpServletResponse;
import java.util.logging.Logger;

//TODO vyhledavani + statistiky - (analyzaPozadavku 1.1.3)
//TODO URGENT opravit login panely. oddelit settings page od eshopu.

public class WicketApplication extends AuthenticatedWebApplication implements ApplicationContextAware {
    private final static Logger logger = Logger.getLogger(WicketApplication.class.getName());
    private ApplicationContext ctx;

    /**
     * Constructor
     */
    public WicketApplication() {
    }


    @Override
    protected void init() {
        super.init();
        // Set default error pages for HTML markup
//		getApplicationSettings().setPageExpiredErrorPage(PageExpiredErrorPage.class);
//		getApplicationSettings().setInternalErrorPage(InternalErrorPage.class);
//		getApplicationSettings().setAccessDeniedPage(LoginPage.class);


//  @AuthorizeInstantiation("ADMIN")
// MetaDataRoleAuthorizationStrategy.authorize(panel, RENDER, "ADMIN");
// @AuthorizeAction(action = Action.RENDER, roles = Roles.ADMIN)
        getSecuritySettings().setAuthorizationStrategy(
                new RoleAuthorizationStrategy(new UserRolesAuthorizer()));
        MetaDataRoleAuthorizationStrategy.authorize(OrderPage.class, "CUSTOMER, ADMIN");
        MetaDataRoleAuthorizationStrategy.authorize(RegisteredWizardPage.class, "CUSTOMER, ADMIN");
        MetaDataRoleAuthorizationStrategy.authorize(SimpleProductEshopPage.class, "CUSTOMER, ADMIN");
        MetaDataRoleAuthorizationStrategy.authorize(MultipleProductsEshopPage.class, "CUSTOMER, ADMIN");
        MetaDataRoleAuthorizationStrategy.authorize(UserSettingsPage.class, "CUSTOMER, ADMIN");
//        MetaDataRoleAuthorizationStrategy.authorize(CommentsPanel.class, "CUSTOMER, ADMIN");
//        MetaDataRoleAuthorizationStrategy.authorize(LadderPanel.class, "CUSTOMER, ADMIN");
//        MetaDataRoleAuthorizationStrategy.authorize(ProductPanel.class, "CUSTOMER, ADMIN");
//        MetaDataRoleAuthorizationStrategy.authorize(RelatedProductsPanel.class, "CUSTOMER, ADMIN");
//        MetaDataRoleAuthorizationStrategy.authorize(ShoppingCartPanel.class, "CUSTOMER, ADMIN");
//        MetaDataRoleAuthorizationStrategy.authorize(CategoryTreePanel.class, "CUSTOMER, ADMIN");

        MetaDataRoleAuthorizationStrategy.authorize(AdminPage.class, "ADMIN");
//        MetaDataRoleAuthorizationStrategy.authorize(AdminBasePage.class, "ADMIN");


//        getRequestCycleSettings().setGatherExtendedBrowserInfo(true);
        addComponentInstantiationListener(new SpringComponentInjector(this, ctx, true));
//        SMTPServer smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(new MySimpleMessageListener()));
//        smtpServer.setPort(25);
//        smtpServer.start();

        getMarkupSettings().setDefaultMarkupEncoding("UTF-8");
        getRequestCycleSettings().setResponseRequestEncoding("UTF-8");

        getSharedResources().add("imageResource", new ImageResource());
        mountSharedResource("/resource/images", new ResourceReference("imageResource").getSharedResourceKey());

        new AnnotatedMountScanner().scanPackage("web").mount(this);

        if (WicketApplication.DEVELOPMENT.equalsIgnoreCase(getConfigurationType())) {
            getResourceSettings().setResourcePollFrequency(Duration.ONE_SECOND);
//            getResourceSettings().addResourceFolder("C:/Users/user/Desktop/trunk/SpringShop/src/main/java");
//            getResourceSettings().addResourceFolder("C:/Users/user/Desktop/trunk/SpringShop/src/main/java/shop/web");

            getResourceSettings().addResourceFolder("D:/__krasa/WicketPack/WicketApp/src/main/java/web");
//            getResourceSettings().addResourceFolder("D:/__krasa/WicketPack/WicketApp/src/main/java/shop");
//            getResourceSettings().addResourceFolder("D:/__krasa/WicketPack/WicketApp/src/main/java/");
//            getResourceSettings().addResourceFolder("C:/Documents and Settings/Death-Filip/Dokumenty/NetBeansProjects/googleSVN/SpringShop/src/main/java/shop/web");
//            getResourceSettings().addResourceFolder("C:/Documents and Settings/Death-Filip/Dokumenty/NetBeansProjects/googleSVN/SpringShop/src/main/java/shop");
//            getResourceSettings().addResourceFolder("C:/Documents and Settings/Death-Filip/Dokumenty/NetBeansProjects/googleSVN/SpringShop/src/main/java/");

            IRequestLoggerSettings reqLogger = Application.get().getRequestLoggerSettings();
            reqLogger.setRequestLoggerEnabled(true);
            reqLogger.setRecordSessionSize(true);
            reqLogger.setRequestsWindowSize(200);
//
//            HtmlValidationResponseFilter htmlvalidator = new HtmlValidationResponseFilter();
//            htmlvalidator.setIgnoreAutocomplete(true);
//            htmlvalidator.setIgnoreKnownWicketBugs(true);
//            getRequestCycleSettings().addResponseFilter(htmlvalidator);
        }


    }

    public static WicketApplication getInstance() {
        return ((WicketApplication) WebApplication.get());
    }

    public Object getBean(String name) {
        if (name == null) {
            throw new IllegalArgumentException();
        }

        return ctx.getBean(name);
    }


    /* (non-Javadoc)
     * @see org.apache.wicket.Application#getHomePage()
     */

    @Override
    public Class<? extends Page> getHomePage() {
        return HomePage.class;
    }

//    @Override
//    protected void setUpHive() {
//        SwarmPolicyFileHiveFactory factory = new SwarmPolicyFileHiveFactory(getActionFactory());
//        try {
//            factory.addPolicyFile(getServletContext().getResource("/WEB-INF/security.hive"));
//            factory.setAlias("hp", "shop.web.CmsHomePage");
//            factory.setAlias("sp", "shop.web.SecurePage3");
//            factory.setAlias("sp2", "shop.web.AdminPage");
//            factory.setAlias("msp", "shop.web.MySecurePage");
//
//            factory.setAlias("emp", "shop.web.eshop.MultipleProductsEshopPage");
//            factory.setAlias("esp", "shop.web.eshop.SimpleProductEshopPage");
//            factory.setAlias("order", "shop.web.eshop.order.OrderPage");
//            factory.setAlias("erw", "shop.web.eshop.wizard.RegisteredWizardPage");
//
//            factory.setAlias("adminPage", "shop.web.admin.AdminPage");
//
//        } catch (MalformedURLException e) {
//            throw new WicketRuntimeException(e);
//        }
//
//        HiveMind.registerHive(getHiveKey(), factory);
//    }

//    @Override
//    protected Object getHiveKey() {
//        return getServletContext().getContextPath();
//    }


    @Override
    public RolesSession newSession(
            Request request, Response response) {
        return new RolesSession(request);
    }

    @Override
    protected Class<? extends AuthenticatedWebSession> getWebSessionClass() {
        return RolesSession.class;

    }

    @Override
    protected Class<? extends WebPage> getSignInPageClass() {
        return LoginPage.class;
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
    }
    // for clean URLs without jsession id

//    @Override
//    protected WebResponse newWebResponse(final HttpServletResponse servletResponse) {
//        return CleanWebResponse.getNew(this, servletResponse);
//    }

    @Override
    protected WebResponse newWebResponse(final HttpServletResponse servletResponse) {
        return CleanWebResponse.getNew(this, servletResponse, true);
    }

// for ajax times or links not to expire the page

    @Override
    protected IRequestCycleProcessor newRequestCycleProcessor() {
        return new AjaxWebRequestCycleProcessor();
    }


}
